package cn.itcast.controller;

import cn.itcast.domain.User;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/demo")
public class ControllerDemo {
    @RequestMapping("/a")
    public String demo1(User user, Model model) {
        System.out.println(user);
        model.addAttribute("user", user);
        return "success";
    }
    @RequestMapping("/a1")
    public void demo( @RequestBody String body)  {
        System.out.println(body);

    }

    @RequestMapping("/a/{id}")
    public String demo2(@PathVariable(name = "id") int id, Model model) {
      /*通过id查询用户数据，restful风格，前端数据通过'/1'而不是id=1来传值，通过请求方式
        和占位符{}来区分不同的方法，缓存都在/a目录下，操作更简洁，*/
        return "success";
    }

    @RequestMapping("/b/{name}")
    public void demo3(HttpServletResponse res, HttpServletRequest req, @PathVariable("name") String name) throws Exception {
        System.out.println(name);
        //req.setCharacterEncoding("utf-8");
        //res.setContentType("text/html;charset=utf-8");
        //response响应只能使用一种输出流
        res.getOutputStream().write("你好".getBytes("UTF-8"));//字节流
        //res.getWriter().print("你好!!");
    }

    @RequestMapping("/c")
    public ModelAndView demo4() {
        ModelAndView view = new ModelAndView();
        view.addObject("view", "view");
        //设置返回的视图页面
        view.setViewName("success");
        return view;
    }

    //造一些数据模拟后台查询
    private List<User> list = new ArrayList<>();

    public ControllerDemo() {
        list.add(new User("jack", "ii", "女"));
        list.add(new User("jac二k", "i额i", "男"));
        list.add(new User("jack微软", "iiw", "女"));
        list.add(new User("jack人", "ii微软", "女"));
        list.add(new User("ja额ck", "i33i", "女"));
    }

    @RequestMapping("/ajax")
    //@ResponseBody
    public @ResponseBody List<User> ajax() {
        System.out.println("调用了方法");
        return list;
    }
}
